package com.zzzyh.forumsystemclient.services.impl;


import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static io.lettuce.core.pubsub.PubSubOutput.Type.message;

@Service
@Slf4j
public class DashScopeAIService {

    @Value("${dashscope.api.url}")
    private String apiUrl;

    @Value("${dashscope.api.key}")
    private String apiKey;

    @Value("${dashscope.api.model}")
    private String model;

    @Value("${dashscope.api.timeout}")
    private int timeout;

    @Value("${dashscope.api.demoId}")
    private String demoId;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 调用阿里云百炼平台API生成文章摘要
     *
     * @param content 文章内容
     * @return 生成的摘要
     */
    public String generateSummary(String content) {
        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);
            requestBody.put("input", buildInput(content));
            requestBody.put("parameters", buildParameters());

            // 发送请求
            String response = sendRequest(requestBody);

            // 解析响应
            JsonNode jsonNode = objectMapper.readTree(response);
            JsonNode output = jsonNode.get("output");
            if (output != null) {
                JsonNode text = output.get("text");
                if (text != null) {
                    return text.asText();
                }
            }
        } catch (Exception e) {
            log.error("调用阿里云百炼平台API生成摘要失败", e);
        }
        return null;
    }

    /**
     * 构建输入内容
     *
     * @param content 文章内容
     * @return 输入内容
     */
    private Map<String, Object> buildInput(String content) {
        Map<String, Object> input = new HashMap<>();

        List<Map<String, String>> messages = new ArrayList<>();

        // 系统消息 - 定义AI的行为
        Map<String, String> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "你是一个专业的文章摘要生成器。请为用户提供的文章内容生成简洁明了的摘要，摘要长度不超过200个字。");
        messages.add(systemMessage);

        // 用户消息 - 包含文章内容
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", "请为以下文章生成摘要:\n\n" + content);
        messages.add(userMessage);

        input.put("messages", messages);
        return input;
    }

    /**
     * 构建参数
     *
     * @return 参数
     */
    private Map<String, Object> buildParameters() {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("temperature", 0.7);
        parameters.put("max_tokens", 300);
        parameters.put("result_format", "text");
        return parameters;
    }

    /**
     * 发送请求到阿里云百炼平台API
     *
     * @param requestBody 请求体
     * @return API响应
     */
    private String sendRequest(Map<String, Object> requestBody) {
        try {
            RestTemplate restTemplate = new RestTemplate();

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);
            headers.set("X-DashScope-SSE", "disable");

            // 创建请求实体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            // 发送POST请求
            ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, requestEntity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                return response.getBody();
            } else {
                log.error("阿里云百炼平台API调用失败，状态码: {}", response.getStatusCode());
            }
        } catch (Exception e) {
            log.error("发送请求到阿里云百炼平台API时发生异常", e);
        }
        return null;
    }

    /**
     * 与AI进行对话
     *
     * @param cleanContent 清洗后的内容
     * @return AI的回复
     */
    public String chatWithAI(String cleanContent) {
        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);
            requestBody.put("input", buildChatInput(cleanContent));
            requestBody.put("parameters", buildChatParameters());

            // 发送请求
            String response = sendRequest(requestBody);

            // 解析响应
            JsonNode jsonNode = objectMapper.readTree(response);
            JsonNode output = jsonNode.get("output");
            if (output != null) {
                JsonNode text = output.get("text");
                if (text != null) {
                    return text.asText();
                }
            }
        } catch (Exception e) {
            log.error("调用阿里云百炼平台API进行对话失败", e);
        }
        return null;
    }
    /**
     * 构建对话输入内容
     *
     * @param message 用户消息
     * @return 输入内容
     */
    private Map<String, Object> buildChatInput(String message) {
        Map<String, Object> input = new HashMap<>();

        List<Map<String, String>> messages = new ArrayList<>();

        // 系统消息 - 定义AI的行为
        Map<String, String> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "你是一个论坛聊天助手，用户在论坛聊天室中向你提问，你需要给出友好、简洁、有帮助的回答，回答长度不超过100个字。");
        messages.add(systemMessage);

        // 用户消息 - 包含用户问题
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", message);
        messages.add(userMessage);

        input.put("messages", messages);
        return input;
    }

    /**
     * 构建对话参数
     *
     * @return 参数
     */
    private Map<String, Object> buildChatParameters() {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("temperature", 0.8);
        parameters.put("max_tokens", 150);
        parameters.put("result_format", "text");
        return parameters;
    }

    public  String appCall(String question)
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量，可用百炼API Key将下行替换为：.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中，以减少API Key泄露风险。
                .apiKey(apiKey)
                .appId(demoId)
                .prompt(question)
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);
//        log.info("result: {}", result.getOutput().getText());
        return result.getOutput().getText();
    }
}
